<?php

namespace App\Http\Controllers\Api\Third;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use DB;

//山东淄博千恒四达检测接口
class SiDaJianCeApiController extends Controller
{
    private $BaseUrl = "http://ip:port/";
    private $UploadUrl = "/qh_lims/sida/carApi/upload";
    private $AddUrl = "/qh_lims/sida/carApi/add";

    public function __construct($BaseUrl){
        $this->BaseUrl = $BaseUrl;
    }

    //检测存量工器具送检安全工器具试验结果保存
    public function saveGqjBookTestInfo($inputDatas){
        $setting = getCache('setting');
        // 对接步骤：
        // 1、先上传报告文档 获得报告存储路径
        // 2、再上传数据文档 获得数据存储路径
        // 3、把2个文件路径填充到 试验情况数据中提交
        $contract_id = $inputDatas['contract_id'];
        $contract = DB::table('a_contract as a')
            ->leftJoin('a_status_time as b','a.id','=','b.contract_id')
            ->where('a.id',$contract_id)
            ->select('a.*','b.test_end','b.report_end','b.test_start')
            ->first();
        $gy = DB::table('a_contract_gaiyao')->where('contract_id',$contract_id)->select('count','tool_name')->get()->toArray();
        $managers = DB::table('a_item_data')->where('contract_id',$contract_id)->distinct()->pluck('managers')->toArray();
        // dd($managers);
        $mans1 = $mans2 = [];
        foreach ($managers as $manager) {
            $mans = explode('，',$manager);
            $mans1[] = data_get($mans,0,'');
            $mans2[] = data_get($mans,1,'');
        }
        $mans = array_filter(array_unique(array_merge($mans1,$mans2)));
        // $filePath = "storage/reports/{$contract->batchNum}.xls";
        $filePath = "storage/reports/{$contract->batchNum}.docx";
        if (!file_exists($filePath)) {
            dd($filePath);
            return '报告未生成';
        }
        list($code,$report) = $this->upload_file($filePath);
        if ($code == 0) {
            return '报告上传失败！'.$report;
        }
        $storage = 'storage/';
        $filePath = "reports/原始记录_批次{$contract->batchNum}.xls";
        if (!file_exists($filePath)) {
            $ExportOrigin = new \App\Http\Controllers\Admin\ExportOrigin\PublicController();
            request()->offsetSet('contract_id',$contract_id);
            $ExportOrigin->export(request(),"reports/原始记录_批次{$contract->batchNum}.xls");
        }
        list($code,$testData) = $this->upload_file($storage.$filePath);
        // dd($code,$testData);
        if ($code == 0) {
            return '原始记录上传失败！'.$testData;
        }
        $disk = Storage::disk('public');
        $disk->delete($filePath);
        // $report = 'carfile/220001_1671619416119.xls';
        // $testData = 'carfile/220001_1671619416119.xls';
        $data = [
          "carName"=> "安全工器具检测车1",
          "client"=> $contract->entrusted_company,
          "contacts"=> $contract->client_contact,
          "createBy"=> $contract->creator,
          "createTime"=> $contract->created_at,
          "endTime"=> $contract->test_end,
          "id"=> "",
          "report"=> $report,
          "reportNo"=> $setting['setting']->report_num_pre.$contract->batchNum,
          "reportTime"=> $contract->report_end,
          "sampleModel"=> "",
          "sampleName"=> implode(',',array_unique(array_column($gy,'tool_name'))),
          "sampleNumber"=> array_sum(array_column($gy,'count')),
          "startTime"=> $contract->test_start,
          "sysOrgCode"=> "",
          "telephone"=> $contract->client_tel,
          "testData"=> $testData,
          "testItems"=> "",
          "testMan"=> implode(',',$mans),
          "updateBy"=> "",
          "updateTime"=> ""
        ];

        $headers = ['Content-type:application/json;charset=utf-8'];
        // dd($data);
        try{
            $res = json_decode(curl($this->BaseUrl.$this->AddUrl,json_encode($data),$headers),true);
            // dd($data,$res);
            if($res['success'] == true && $res['code'] == 200){
                return 1;
            }
            return $res['message'];
        }catch(\Exception $e){
            return $e->getMessage();
        }
    }

    //上传文档
    // @var  struing  $file  上传文件的路径和文件名
    private function upload_file($r_file)
    {
        $file = public_path($r_file);
        $file = array(
            "file"=>new \CURLFile($file),
            'password'=>'sidapassword9571',
        );//文件路径，前面要加@，表明是文件上传.
        $curl = curl_init();
        // dd($this->BaseUrl.$this->UploadUrl);
        curl_setopt($curl, CURLOPT_URL,$this->BaseUrl.$this->UploadUrl);
        curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl,CURLOPT_POSTFIELDS,$file);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        $result = curl_exec($curl);  //$result 获取页面信息 
        curl_close($curl);
        $result = json_decode($result);
        $msg = data_get($result,'message','');
        if (data_get($result,'success','') == true && data_get($result,'code','') == 0) {
            return [1,$msg];
        }else{
            return [0,$msg];
        }
    }
}
